<script setup>
  import emptyIcon from '@/assets/image/com_empty.png'
  import {queryCart, updateCart, delCart} from '@/api/cart'
  import useCommodityStore from '@/store/modules/commodity'
  import useSettingStore from '@/store/modules/setting'
  import { showToast } from 'vant'

  const useStore = useCommodityStore()
  const {proxy} = getCurrentInstance()
  const router = useRouter()
  const currency = ref(useSettingStore().global.currencySymbol || '')

  // 管理购物车
  const manage = ref(false)
  const loading = ref(false)
  const cartData = ref({
    total: 0,
    rows: []
  })
  // 全选
  const checkedAll = ref(false)
  const open = ref(false)
  // 缓存要删除的商品
  const delItem = ref({})

  // 总价格
  const totalPrice = computed(() => {
    let r = 0
    cartData.value.rows.forEach(it => {
      if(it.checked) {
        r+=it.num*it.price
      }
    })
    return r
  })

  function refreshALl() {
    checkedAll.value = !cartData.value.rows.some(it => !it.checked)
  }
  function selectAll(e) {
    cartData.value.rows.forEach(it => {
      it.checked = e
    })
  }
  // 购物车数据
  function initData() {
    loading.value = true
    queryCart().then(r => {
      const {rows, total} = r
      cartData.value = {rows, total}
      loading.value = false
      useStore.getCart(total)
    })
  }
  // 结算或批量删除
  function handleCart() {
    const selectedList = cartData.value.rows.filter(it => !!it.checked)
    if(!selectedList.length) {
      showToast(proxy.$t(`commodity.${manage.value?'del':'buy'}Msg`))
      return
    }
    // 删除
    if(manage.value) {
      handleDel()
    } else {
      const unEffect = selectedList.some(it => it.isLapse===1||it.isShow===0)
      if(unEffect) return showToast(proxy.$t(`commodity.buyTip`))
      router.push({
        path: '/shopping',
        query: {
          cartIds: selectedList.map(it=>it.cartId).join(',')
        }
      })
    }
  }
  // 删除购物车
  function handleDel(item={}) {
    delItem.value = item
    open.value = true
  }
  // 关闭删除确认框
  function cancel() {
    open.value = false
    delItem.value = {}
  }
  // 确认删除
  function confirm() {
    const cartIds = []
    if(delItem.value.cartId) {
      cartIds.push(delItem.value.cartId)
    } else {
      cartData.value.rows.forEach(it => {
        if(it.checked) cartIds.push(it.cartId)
      })
    }
    delCart({cartIds: cartIds.join(',')}).then(r => {
      showToast(proxy.$t('commodity.delSuc'))
      cancel()
      initData()
    })
  }
  // 改变购物车商品数量
  function changeNum(it, v) {
    const {num, cartId} = it
    if(num===1&&v==-1) return
    updateCart({cartId, num: num+v}).then(r => {
      if(v==1) it.num++
      if(v==-1) it.num--
    })
  }

  initData()
</script>

<template>
  <div class="cart">
    <div class="t-cell">
      <div class="m-title">
        {{$t('commodity.cart')}}
        <span>({{cartData.total}})</span>
      </div>
      <div class="fun-text" @click="manage=!manage">{{manage?$t('commodity.finish'):$t('commodity.manage')}}</div>
    </div>
    <div class="card-product" v-if="cartData.total">
      <ul class="pro-list">
        <li v-for="(it, i) in cartData.rows" :key="i" class="pro-item">
          <van-checkbox
            shape="square"
            checked-color="#262626"
            v-model="it.checked"
            @change="refreshALl"
          />
          <div class="img-cell">
            <img :src="it.image"/>
            <div class="uneffect" v-if="it.isLapse===1 || it.isShow===0">
              <div>{{$t(`commodity.${it.isLapse===1?'isLapse':'isShow'}`)}}</div>
            </div>
          </div>
          <div class="pro-info">
            <div class="info-cell">
              <div class="main-title flex-bt">
                <p class="text-overflow">{{it.productName}}</p>
                <p v-if="manage" @click="handleDel(it)">
                  <i class="iconfont icon-guanbi"/>{{$t('commodity.remove')}}
                </p>
              </div>
              <p class="sku"><span>{{$t('commodity.sku')}}：</span>{{it.sku}}</p>
            </div>
            <div class="price-count flex-bt">
              <p><span>{{currency}}</span>{{it.price}}</p>
              <p>
                <span @click="changeNum(it, -1)">－</span>
                <span>{{it.num}}</span>
                <span @click="changeNum(it, 1)">＋</span>
              </p>
            </div>
          </div>
        </li>
      </ul>
      <van-sticky position="bottom">
      <div class="b-box flex-bt">
        <div class="select">
          <van-checkbox
            shape="square"
            checked-color="#262626"
            @click="selectAll(checkedAll)"
            v-model="checkedAll"
          />
          <span>{{$t('commodity.selectAll')}}</span>
        </div>
        <div class="fun-btn">
          <p v-if="!manage">{{$t('commodity.totalNum')}}:<span>{{currency}}{{totalPrice}}</span></p>
          <van-button class="s-btn w-auto" @click="handleCart">{{manage?$t('commodity.del'):$t('commodity.toBuy')}}</van-button>
        </div>
      </div>
      </van-sticky>
    </div>
    <div class="empty" v-if="!cartData.total && !loading">
      <img :src="emptyIcon" alt=""/>
      <p>{{$t('commodity.noCarts')}}</p>
      <router-link to="/index">
        <van-button class="s-btn w-auto h32">{{$t('commodity.continueBuy')}}</van-button>
      </router-link>
    </div>
    <van-popup
      v-model:show="open"
      @close="cancel"
    >
      <div class="modal-con">
        <p>{{$t('common.tip')}}</p>
        <p>{{$t('commodity.delOk')}}</p>
        <van-row gutter="8">
          <van-col span="12">
            <van-button class="s-btn line-btn" @click="cancel">{{$t('common.cancel')}}</van-button>
          </van-col>
          <van-col span="12">
            <van-button class="s-btn" @click="confirm">{{$t('common.confirm')}}</van-button>
          </van-col>
        </van-row>
      </div>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
  .cart {
    padding: 16px;
    .flex-bt {
      display: flex;
      justify-content: space-between;
    }
    .t-cell {
      display: flex;
      justify-content: space-between;
      padding-bottom: 16px;
      border-bottom: 1px solid #E5E5E5;
      .m-title {
        font-size: 18px;
        span {
          font-size: 14px;
          color: #8C8C8C;
          margin-left: 4px;
        }
      }
      .fun-text  {
        font-size: 14px;
      }
    }
    .card-product {
      :deep(.van-checkbox) {
        display: inline-flex;
        vertical-align: middle;
        .van-icon {
          width: 18px;
          height: 18px;
          border: 1px solid #262626;
        }
      }
      .pro-list {
        .pro-item {
          display: flex;
          align-items: start;
          column-gap: 12px;
          padding: 16px 0;
          position: relative;
          &::after {
            content: '';
            height: 1px;
            width: calc(100% - 30px);
            background: #E5E5E5;
            position: absolute;
            bottom: 0;
            left: 30px;
          }
          .img-cell {
            height: 110px;
            width: 98px;
            position: relative;
            img {
              height: 100%;
              width: 100%;
            }
            .uneffect {
              position: absolute;
              width: 100%;
              height: 100%;
              top: 0;
              left: 0;
              background: rgba(255, 255, 255, .5);
              display: flex;
              align-items: center;
              justify-content: center;
              div {
                width: 56px;
                height: 56px;
                background: rgba(0,0,0,0.5);
                border-radius: 50%;
                font-weight: 600;
                font-size: 12px;
                color: #FFFFFF;
                text-align: center;
                line-height: 56px;
              }
            }
          }
          .pro-info {
            width: calc(100% - 140px);
            display: flex;
            height: 110px;
            flex-direction: column;
            justify-content: space-between;
            .info-cell {
              width: 100%;
              .main-title {
                width: 100%;
                align-items: center;
                margin-bottom: 8px;
                p {
                  &:first-child {
                    flex: 2;
                    font-size: 14px;
                    font-weight: 600;
                  }
                  &:nth-child(2) {
                    flex: 1;
                    font-size: 12px;
                    color: #8C8C8C;
                    text-align: right;
                    .iconfont {
                      display: inline-block;
                      transform: translateY(2px);
                    }
                  }
                }
              }
              .sku {
                font-size: 12px;
                span {
                  color: #666666;
                }
              }
            }
            .price-count {
              height: 28px;
              align-items: center;
              p {
                &:nth-child(1) {
                  font-weight: 600;
                  font-size: 14px;
                }
                &:nth-child(2) {
                  display: inline-block;
                  border-radius: 2px;
                  border: 1px #262626 solid;
                  padding: 6px 4px;
                  span {
                    font-size: 12px;
                    &:first-child, &:last-child {
                      font-size: 16px;
                      display: inline-block;
                      height: 16px;
                      width: 16px;
                      text-align: center;
                      line-height: 16px;
                      border-radius: 50%;
                      background: #F5F5F5;
                      color: #A9A9B2;
                      &:hover {
                        cursor: pointer;
                      }
                    }
                    &:last-child {
                      background: #262626;
                      color: #FFFFFF;
                    }
                    &:nth-child(2) {
                      padding: 0 5px;
                      color: #8C8C8C;
                    }
                  }
                }
              }
            }
          }
        }
      }
      .b-box {
        height: 44px;
        align-items: center;
        padding: 8px 0;
        background: #FFFFFF;
        .select {
          font-size: 14px;
          color: #8C8C8C;
          span {
            margin-left: 12px;
          }
        }
        .fun-btn {
          height: 44px;
          display: flex;
          align-items: center;
          p {
            display: inline-block;
            margin-right: 6px;
            font-size: 14px;
            span {
              font-weight: 600;
            }
          }
        }
      }
    }
    .empty {
      text-align: center;
      img {
        width: 100px;
        height: 100px;
        margin-bottom: 4px;
      }
      p {
        font-size: 14px;
        color: #8C8C8C;
        margin-bottom: 12px;
      }
    }
  }
  .van-popup  {
    padding: 24px;
    width: calc(100% - 64px);
    border-radius: 2px;
    .modal-con {
      text-align: center;
      p {
        font-size: 14px;
        margin-bottom: 20px;
        &:nth-of-type(1) {
          font-size: 16px;
          margin-top: 20px;
        }
      }
    }
  }
</style>